package com.learn.springbootcache.service;

import com.learn.springbootcache.bean.ChinaCity;
import com.learn.springbootcache.bean.ChinaCounty;
import com.learn.springbootcache.bean.ChinaProvince;
import com.learn.springbootcache.bean.ChinaRegion;
import com.learn.springbootcache.mapper.ChinaProvinceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Jmy
 * @date 2019/10/18 15:11
 * @email jiaomingyu5778@gmail.com
 */
@CacheConfig(cacheNames = "china_province")
@Service
public class ChinaProvinceService {

    @Autowired
    ChinaProvinceMapper chinaProvinceMapper;

//    @Qualifier("china_province")
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 获取当前系统中，所有的省份信息
     * @return
     */
    @Cacheable(key = "#root.methodName")
    public List<ChinaProvince> findAllList(){
        return chinaProvinceMapper.findAllList();
    }

    /**
     * 返回省下面的区，省ID作为缓存ID
     * @param provinceId
     * @return
     */
    @Cacheable(key = "#p0", unless = "#result.size() == 0")
    public List<ChinaCity> findCityByProvinceId(Integer provinceId){
        return chinaProvinceMapper.findCityByProvinceId(provinceId);
    }

    @Cacheable(key = "#p0", unless = "#result.size() == 0")
    public List<ChinaCounty> findCountyByCityId(Integer cityId){
        return chinaProvinceMapper.findCountyByCityId(cityId);
    }

    @Cacheable(key = "#p0", unless = "#result.size() == 0")
    public List<ChinaRegion> findRegionByCountyId(Integer countyId){
        return chinaProvinceMapper.findRegionByCountyId(countyId);
    }

    public ChinaRegion findRegionById(Integer id){
//        Object chinaRegion = redisTemplate.opsForValue().get(id);
//        if (chinaRegion != null) {
//            return (ChinaRegion) chinaRegion;
//        }
        ChinaRegion chinaRegionNew = chinaProvinceMapper.findRegionById(id);
        redisTemplate.opsForValue().set(id,chinaRegionNew);
        return chinaRegionNew;
    }
}
